//
//  VRWebViewController.m
//  Rebate
//
//  Created by veer on 2017/7/1.
//  Copyright © 2017年 liuye. All rights reserved.
//

#import "VRWebViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import <AddressBook/AddressBook.h>
#import "VRAddressBookTool.h"
#import "VRAlertView.h"
#import "VRUserInfo.h"
#import <CoreTelephony/CTCellularData.h>


@interface VRWebViewController () <UIWebViewDelegate, WebViewJSExport>

@property (nonatomic, weak) UIWebView *webView;

/** 假启动图 */
@property (nonatomic, weak) UIImageView *launchImgView;
/** 假启动图 */
@property (nonatomic, strong) VRAlertView *alertView;

@property(nonatomic,strong)JSContext *jsContext;
//防止多次定位
@property(nonatomic,assign)BOOL isFirstLocation;
@property (nonatomic, strong) CLLocationManager* locationManager;

// 关于定位
@property (nonatomic, strong) CLLocationManager *clMgr;
@property (nonatomic, strong) CLGeocoder *geo;
@property (nonatomic, strong) CLPlacemark *placemark;

@end

@implementation VRWebViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupSubView];
    [self.clMgr startUpdatingLocation];
    [self loadUrlWith:API_homeUrl];
//    [self uploadContactsWithCard:@"296"];
    
    [self requestNetworkPermission];
}

- (void)setupSubView
{
    
    UIWebView *webView = [[UIWebView alloc] init];
    webView.delegate = self;
    webView.frame = self.view.bounds;
    [self.view addSubview:webView];
    self.webView = webView;
    
    // 遮罩
    UIImageView *launchImgView = [[UIImageView alloc] init];
    launchImgView.image = [UIImage imageNamed:@"launch"];
    [self.view addSubview:launchImgView];
    self.launchImgView = launchImgView;
    [launchImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}

- (void)loadUrlWith:(NSString *)urlStr
{
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
    [self.webView loadRequest:request];
}


- (void)jugeNetworkPermission
{
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 9.0) {
        
        // 针对 9.0 以上的iOS系统进行处理
        CTCellularData *cellularData = [[CTCellularData alloc]init];
        
        CTCellularDataRestrictedState state = cellularData.restrictedState;
        switch (state) {
            case kCTCellularDataRestricted:{
                    NSLog(@"----11111----Restricrted-------------");
                    self.launchImgView.hidden = YES;
                    self.launchImgView.hidden = NO;
                    self.alertView = [[VRAlertView alloc] initWithTitle:@"提示" message:@"无线数据服务未开启，请进入系统［设置］> [隐私] > [通讯录]中打开开关" sureBtn:@"去设置" cancleBtn:nil];
                    self.alertView.isHidenAlertBySure = NO;
                    self.alertView.resultIndex = ^(NSInteger index){
                        
                        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        
                        if([[UIApplication sharedApplication] canOpenURL:url]) {
                            
                            NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                            [[UIApplication sharedApplication] openURL:url];
                        }
                    };
                    [self.alertView showXLAlertView];
                }
                break;
            case kCTCellularDataNotRestricted:{
                    NSLog(@"----11111----Not Restricted");
                    self.launchImgView.hidden = YES;
                }
                break;
            case kCTCellularDataRestrictedStateUnknown:{
                    NSLog(@"----11111----Unknown");
                    self.launchImgView.hidden = NO;
                    [self requestNetworkPermission];
                }
                break;
            default:
                break;
        }
        
        
    } else {
        // 针对 9.0 以下的iOS系统进行处理
    }
    
}


- (void)requestNetworkPermission
{
    __weak typeof(self) weakSelf = self;
    CTCellularData *cellularData = [[CTCellularData alloc]init];
    cellularData.cellularDataRestrictionDidUpdateNotifier =  ^(CTCellularDataRestrictedState state){
        //状态改变时进行相关操作
        switch (state) {
            case kCTCellularDataRestricted:
            {
                NSLog(@"----222----Restricrted");
                dispatch_async(dispatch_get_main_queue(), ^{
//                    weakSelf.launchImgView.hidden = NO;
//                    weakSelf.alertView = [[VRAlertView alloc] initWithTitle:@"提示" message:@"无线数据服务未开启，请进入系统［设置］> [隐私] > [通讯录]中打开开关" sureBtn:@"去设置" cancleBtn:nil];
//                    weakSelf.alertView.isHidenAlertBySure = NO;
//                    weakSelf.alertView.resultIndex = ^(NSInteger index){
//
//                        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
//
//                        if([[UIApplication sharedApplication] canOpenURL:url]) {
//
//                            NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
//                            [[UIApplication sharedApplication] openURL:url];
//                        }
//                    };
//                    [weakSelf.alertView showXLAlertView];
                });
                
            }
                break;
            case kCTCellularDataNotRestricted:{
                
                NSLog(@"----222----Not Restricted");
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.webView reload];
//                    weakSelf.alertView.hidden = YES;
//                    weakSelf.launchImgView.hidden = YES;
                });
            }
                break;
            case kCTCellularDataRestrictedStateUnknown:{
                NSLog(@"----222----Unknown");
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    weakSelf.launchImgView.hidden = NO;
//                });
            }
                break;
            default:
                break;
        };
    };
}


- (void)requestContactPermission
{
    // 判断是否授权
    __weak typeof(self) weakSelf = self;
    ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus();
    if (authorizationStatus == kABAuthorizationStatusNotDetermined) {
        // 请求授权
        ABAddressBookRef addressBookRef = ABAddressBookCreate();
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
            if (granted) { // 授权成功
                
                NSLog(@"授权成功！");
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.launchImgView.hidden = YES;
                });
            } else {  // 授权失败
                
                NSLog(@"授权失败！");
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.alertView = [[VRAlertView alloc] initWithTitle:@"提示" message:@"通讯录服务未开启，请进入系统［设置］> [隐私] > [通讯录]中打开开关" sureBtn:@"去设置" cancleBtn:nil];
                    weakSelf.alertView.isHidenAlertBySure = NO;
                    weakSelf.alertView.resultIndex = ^(NSInteger index){
                        
                        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        
                        if([[UIApplication sharedApplication] canOpenURL:url]) {
                            
                            NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                            [[UIApplication sharedApplication] openURL:url];
                            
                        }
                    };
                    [weakSelf.alertView showXLAlertView];
                });
            }
        });
    }else if (authorizationStatus == kABAuthorizationStatusDenied || authorizationStatus == kABAuthorizationStatusRestricted){
        
        NSLog(@"关闭授权！");
        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"您必须授权通讯录权限才能访问此APP" delegate:self cancelButtonTitle:nil otherButtonTitles:@"去设置", nil];
        //        [alert show];
        
        self.alertView = [[VRAlertView alloc] initWithTitle:@"提示" message:@"通讯录服务未开启，请进入系统［设置］> [隐私] > [通讯录]中打开开关" sureBtn:@"去设置" cancleBtn:nil];
        self.alertView.isHidenAlertBySure = NO;
        self.alertView.resultIndex = ^(NSInteger index){
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            
            if([[UIApplication sharedApplication] canOpenURL:url]) {
                
                NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
                
            }
        };
        [self.alertView showXLAlertView];
    }else{
        
        self.launchImgView.hidden = YES;
    }
    
    
}


#pragma mark - net
/** 上传联系人 */
- (void)uploadContactsWithCard:(NSString *)card
{
    // hud
    [SVProgressHUD setDefaultMaskType:(SVProgressHUDMaskTypeCustom)];
    [SVProgressHUD showWithStatus:@"上传数据中..."];
    
    NSMutableArray *contactDicts = [VRAddressBookTool getContactsWithBlock:nil];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    //    NSDictionary *dict = @{@"datas":@"123"};
    NSArray *array = @[@{@"name" : @"panxx1", @"number" : @""},
                       @{@"name" : @"", @"number" : @"18257149139"},
                       @{@"name" : @"panxx3", @"number" : @"18257149139"},
                       @{@"name" : @"panxx4", @"number" : @"18257149139"},
                       @{@"name" : @"panxx5", @"number" : @"18257149139"}];
    //    param[@"datas"] = @"[{\"name\":\"panxx\", \"phone\":\"18257149139\"}]";
    NSString *jsonStr = [self convertToJsonData:contactDicts];
    param[@"card"] = card;
    param[@"datas"] = jsonStr;
    
    VRLog(@"param:%@", param);
    
    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
    
    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", nil];
    
    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;
    
    sessionMgr.requestSerializer=[AFHTTPRequestSerializer serializer];
    
    // 设置超时时长
    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
//    sessionMgr.requestSerializer.timeoutInterval = 20.0;
    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    __weak typeof(self) weakSelf = self;
    [sessionMgr POST:API_upLoadContact parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // hud
        [SVProgressHUD dismiss];
        VRLog(@"responseObject:%@", responseObject);
        
        NSInteger struts = [responseObject[@"struts"] integerValue];
        if (struts == 3){
            
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            [weakSelf loadUrlWith:API_upRefreshUrl];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        VRLog(@"error:%@", error);
        [SVProgressHUD dismiss];
        if (error.code == -1009) {  // 网络连接错误
            
            [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
        }else if (error.code == -1001){ // 链接超时
            
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"请求错误"];
        }
    }];
    
    [sessionMgr.operationQueue cancelAllOperations];
}

/** 上传联系人 */
- (void)uploadLocationWithCard:(NSString *)card
{
    // hud
    [SVProgressHUD showWithStatus:@"上传数据中..."];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"card"] = card;
    param[@"lng"] = [NSString stringWithFormat:@"%.3lf", [VRUserInfo shareUserInfo].longitude];
    param[@"lat"] = [NSString stringWithFormat:@"%.3lf", [VRUserInfo shareUserInfo].latitude];
    
    VRLog(@"param:%@", param);
    
    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
    
    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", nil];
//    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"text/html", nil];
    
    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;
    
    sessionMgr.requestSerializer=[AFHTTPRequestSerializer serializer];
    
    // 设置超时时长
    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionMgr.requestSerializer.timeoutInterval = 10.0;
    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [sessionMgr POST:API_upLoadLocation parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // hud
        [SVProgressHUD dismiss];
        VRLog(@"responseObject:%@", responseObject);
        
        NSInteger struts = [responseObject[@"code"] integerValue];
        if (struts == 0){
            
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            [self loadUrlWith:API_upRefreshUrl];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        VRLog(@"error:%@", error);
        [SVProgressHUD dismiss];
        if (error.code == -1009) {  // 网络连接错误
            
            [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
        }else if (error.code == -1001){ // 链接超时
            
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"请求错误"];
        }
    }];
    
    [sessionMgr.operationQueue cancelAllOperations];
}


#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    [self createJSBridge];
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    return YES;
}


- (void)createJSBridge
{
    JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.jsContext = jsContext;
    jsContext[@"js"] = self;
    //传定位信息
    jsContext[@"upLoadAddressBook"] = ^(NSObject *card){

        NSLog(@"card:%@", card);
    };

    jsContext[@"onUploadLocation"] = ^(NSString *card){

        NSLog(@"card:%@", card);
    };
}

- (void)upLoadAddressBook:(NSString *)card
{
    NSLog(@"card:%@", card);
    [self uploadContactsWithCard:card];
}

- (void)onUploadLocation:(NSString *)card
{
    NSLog(@"card:%@", card);
    [self uploadLocationWithCard:card];
}


#pragma mark cllocation代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    CLLocation *loc = locations.lastObject;
    [VRUserInfo shareUserInfo].latitude = loc.coordinate.latitude;
    [VRUserInfo shareUserInfo].longitude = loc.coordinate.longitude;
    
    NSLog(@"locationManager:lat:%lf, lng:%lf", loc.coordinate.latitude, loc.coordinate.longitude);
    
    [self.clMgr stopUpdatingLocation];
}


- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        
        self.alertView = [[VRAlertView alloc] initWithTitle:@"提示" message:@"定位服务未开启，请进入系统［设置］> [隐私] > [位置]中打开开关" sureBtn:@"去设置" cancleBtn:nil];
        self.alertView.isHidenAlertBySure = NO;
        self.alertView.resultIndex = ^(NSInteger index){
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            
            if([[UIApplication sharedApplication] canOpenURL:url]) {
                
                NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
                
            }
        };
        [self.alertView showXLAlertView];
    }else if (status != kCLAuthorizationStatusNotDetermined){
        
        //        self.launchImgView.hidden = YES;
        [self requestContactPermission];
    }
}


#pragma mark - tool
// 字典转json字符串方法

-(NSString *)convertToJsonData:(id)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0, jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}


#pragma mark - setter && getter
- (CLLocationManager *)clMgr
{
    if (nil == _clMgr) {
        _clMgr = [[CLLocationManager alloc] init];
        _clMgr.delegate = self;
        _clMgr.desiredAccuracy = kCLLocationAccuracyBest;
        //        _clMgr.allowsBackgroundLocationUpdates = YES;
        if ([_clMgr respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            NSLog(@"requestAlwaysAuthorization");
            [_clMgr requestAlwaysAuthorization];
        }
        
        //开始定位，不断调用其代理方法
        [_clMgr requestWhenInUseAuthorization];
    }
    return _clMgr;
}


@end
